import os
import sys



BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
#接后续代码

import time
import pymysql
import datetime
import os.path


mydb = pymysql.connect(
    host="localhost",  # 默认用主机名
    port=3306,
    user="root",  # 默认用户名
    password="szu@2022",  # mysql密码
    database='db_revit_v3',  # 库名
    charset='utf8'  # 编码方式
)

mycursor = mydb.cursor()

def getTime():
    curr_time = datetime.datetime.now()
    create_time=datetime.datetime.strftime(curr_time,'%Y-%m-%d %H:%M:%S')
    return create_time

def releaseTask():
    id = getTaskID()
    query = "update t_task set step = %s, status=%s where task_id = %s "
    value = (2,0,id)
    mycursor.execute(query,value)
    mydb.commit()
    print("手动发布任务，任务已发布")

def getErrIDs():
    query = "select task_id from t_task where status = 2"
    mycursor.execute(query)
    mydb.commit()
    results = mycursor.fetchall()
    if not results:
        return None
    id = results[0][0]
    # print(id)
    return id

def getMesIDs():
    query = "select task_id from t_task where status = 0"
    mycursor.execute(query)
    mydb.commit()
    results = mycursor.fetchall()
    for result in range(len(results)):
        if len(results[result]) == 1:
            id = results[result][0]
            # print(id)
            return id
        else:
            print("有多和status = 0")
            break

# 检测到任务，获取ID
def getTaskID():
    query = "select task_id from t_task where status = 0"
    mycursor.execute(query)
    mydb.commit()
    results = mycursor.fetchall()
    # print(results)
    if not results:
        return None
    id = results[0][0]
    # print(id)
    return id

# 检测任务是否step = 2
def checkTask():
    id = getTaskID()
    print("等待step = 2 的任务")
    query = "select step from t_task where task_id = %s and step = %s"
    value = (id, 2)
    mycursor.execute(query, value)
    mydb.commit()
    step = mycursor.fetchall()
    if not step:
        return None,None;
    if step != []:
        step = step[0][0]
        return id, step


def ID2path(id):
    data_path = "C:/revit_data/" + str(id) + "/revit_data.xml"
    config_path = "C:/revit_data/" + str(id) + "/user_config.xml"
    order_path = "C:/revit_data/" + str(id) + "/revit_order.xml"
    # print(data_path, config_path, order_path)
    return [config_path, data_path, order_path]

def updateTime():
    id = getTaskID()
    time = getTime()
    query = "update t_task set update_time = %s where task_id = %s "
    mycursor.execute(query,(time,id))
    mydb.commit()
    print("时间已更新：",time)

def endTime():
    id = getTaskID()
    time = getTime()
    query = "update t_task set end_time = %s where task_id = %s and (status = %s or status = %s)"
    mycursor.execute(query,(time,id,1,2))
    mydb.commit()
    print("时间已更新：",time)

def setStatus(id,status):
    query = "update t_task set status = %s where task_id = %s "
    mycursor.execute(query,(status,id))
    mydb.commit()
    updateTime()

def updateStatus():
    id, step = checkTask()
    path = "C:/revit_data/"+ str(id)+ "/revit_order_new.xml"
    # path = "C:/revit_data/1/revit_order_new.xml"
    isPath = os.path.exists(path)
    if isPath:
        print("文件存在：", path)
        query = "update t_task set step = %s, status = %s where task_id = %s "
        mycursor.execute(query, (3, 0, id))
        mydb.commit()
        print("step 2 结束，设置 step = 3")
        updateTime()

# 当status = 0或1 时，输出任务进度
def message_info(message):
    id = getMesIDs()
    query = "update t_task set progress_info = %s where task_id = %s and (status = %s or status = %s)  "
    mycursor.execute(query, (message, id, 0, 1))
    mydb.commit()
    print("任务推进中，progress_info已更新")
    updateTime()

# 当status = 2 时，调用该函数
def err_info(err):
    id = getErrIDs()
    query = "update t_task set progress_info = %s where task_id = %s and status = %s "
    mycursor.execute(query, (err, id, 2))
    mydb.commit()
    print("任务出错，progress_info已更新")
    updateTime()

# 当status = 0或1 时，输出任务进度
def progress(i,all):
    i += 1
    id = getMesIDs()
    pro_mes = i * 100 / all
    query = "update t_task set progress = %s where task_id = %s and status = %s "
    mycursor.execute(query, (int(pro_mes), id, 0))
    mydb.commit()
    print("任务推进中，progress已更新")
    updateTime()

# 当status = 0,1,2 时，调用该函数
def info(err):
    id = getErrIDs()
    query = "update t_task set progress_info = %s where task_id = %s "
    mycursor.execute(query, (err, id))
    mydb.commit()
    print("任务出错，progress_info已更新")
    updateTime()

def watchStep2():
    while True:
        time.sleep(2)
        id, step = checkTask()
        # print(id)
        if step==None:
            continue;
        # if step != 2:
        #     print("等待 step = 2 时的任务")
        if step == 2:
            print("任务id为：",id)
            print("查询到step = 2的任务，检查文件是否存在")
            paths = ID2path(id)
            # 若出现文件不存在，mis赋值为1
            mis = 0
            for path in paths:
                isPath = os.path.exists(path)
                if isPath:
                    print("路径检测完成，文件存在：", path)
                else:
                    mis = 1
                    print("找不到文件：", path)
            if mis == 0:
                try_main(paths,id)
            if (mis == 1):
                print("step 1 结束后，未找到所有所需文件，设置status = 2")
                query = "update t_task set status = %s where task_id = %s"
                value = (2,id)
                mycursor.execute(query, value)
                err_info("未找到所需文件！")
                mydb.commit()
                break
            # print(paths)
            # main(paths);
            # print("revit_order -> revit_order_new")
            updateStatus()


if __name__ == '__main__':
    # 检测数据库任务，开启事务
    # releaseTask()
    watchStep2()